<template>
  <view class="page-body">
    <view class="page-section">
      <view class="page-section-title">订单信息</view>
      <u-form @submit="onSubmit">
        <u-form-item label="预约店铺" required>
          <u-select v-model="store" placeholder="请选择" :options="storeOptions"></u-select>
        </u-form-item>
        <u-form-item label="预约房间" required>
          <u-select v-model="room" placeholder="请选择" :options="roomOptions"></u-select>
        </u-form-item>
        <u-form-item label="手机号码" required>
          <u-input v-model="phone" placeholder="请输入手机号码"></u-input>
        </u-form-item>
        <view class="form-note">新用户需登录微信小程序【麻艺星】，授权用户手机号</view>
        <view class="page-section-title">预约时间</view>
        <u-form-item label="预约开始时间" required>
          <u-datetime-picker v-model="startTime" type="datetime" placeholder="yyyy-MM-dd HH:mm:ss"></u-datetime-picker>
        </u-form-item>
        <u-form-item label="预约结束时间" required>
          <u-datetime-picker v-model="endTime" type="datetime" placeholder="yyyy-MM-dd HH:mm:ss"></u-datetime-picker>
        </u-form-item>
        <view class="form-actions">
          <u-button type="primary" @click="onSubmit">保存</u-button>
          <u-button type="error" @click="onCancel">关闭</u-button>
        </view>
      </u-form>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      store: '',
      room: '',
      phone: '',
      startTime: '',
      endTime: '',
      storeOptions: [],
      roomOptions: [],
      pageNum: 1,
      pageSize: 10
    }
  },
  async created() {
    await this.initData()
  },
  methods: {
    async initData() {
      await this.getStoreList()
      await this.getRoomList()
    },
    getStoreList() {
      uni.$u.http.post('/system/merchant/mchs', {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(res => {
        const storeList = res.data.list || []
        this.storeOptions = storeList.map(item => ({
          label: item.name,
          value: item.id
        }))
      }).catch(err => {
        uni.$u.toast('获取店铺列表失败')
      })
    },
    getRoomList() {
      uni.$u.http.post('/system/room/list', {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(res => {
        const roomList = res.data.list || []
        this.roomOptions = roomList.map(item => ({
          label: item.name,
          value: item.id
        }))
      }).catch(err => {
        uni.$u.toast('获取房间列表失败')
      })
    },
    onSubmit() {
      if (!this.validateForm()) return
      
      uni.$u.http.post('/system/order/create', {
        storeId: this.store,
        roomId: this.room,
        phone: this.phone,
        startTime: this.startTime,
        endTime: this.endTime
      }).then(res => {
        uni.$u.toast('预约成功')
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }).catch(err => {
        uni.$u.toast('提交失败')
      })
    },
    validateForm() {
      if (!this.store) {
        uni.$u.toast('请选择预约店铺')
        return false
      }
      if (!this.room) {
        uni.$u.toast('请选择预约房间')
        return false
      }
      if (!this.phone) {
        uni.$u.toast('请输入手机号码')
        return false
      }
      if (!this.startTime) {
        uni.$u.toast('请选择开始时间')
        return false
      }
      if (!this.endTime) {
        uni.$u.toast('请选择结束时间')
        return false
      }
      return true
    },

    // timepicker
    	//开始时间选择完成
			confirmTimePickerStart(e) {
				let houre = e.value[0].replaceAll('时', '');
				let minute = e.value[1].replaceAll('分', '');
				this.showTimePickerStart = false;
				this.ydBoxIndex = 10075;
				console.log("开始时间选择完成this.timeChangeForm:", this.timeChangeForm);
				let _year = uni.$u.timeFormat(this.timeChangeForm.startTime, 'yyyy');
				let _month = uni.$u.timeFormat(this.timeChangeForm.startTime, 'mm');
				let _day = uni.$u.timeFormat(this.timeChangeForm.startTime, 'dd')

				// let day = new Date(uni.$u.timeFormat(this.timeChangeForm.startTime, 'yyyy-mm-dd') + ' ' + houre + ':' +
				// 	minute + ':00');

				let day = new Date(_year, _month - 1, _day, houre, minute, 0);

				this.timeChangeForm.startTime = day;
				this.timeChangeForm.startTimeStr = uni.$u.timeFormat(this.timeChangeForm.startTime,
					'hh:MM');

				//刷新预约结束时间
				const nextHours = parseInt(houre) + parseInt(this.timeChangeForm.Hours);
				let stime = deepClone(this.timeChangeForm.startTime);
				let _stime = stime.setHours(nextHours);
				let _s_year = uni.$u.timeFormat(_stime, 'yyyy');
				let _s_month = uni.$u.timeFormat(_stime, 'mm');
				let _s_day = uni.$u.timeFormat(_stime, 'dd');
				let _s_houre = uni.$u.timeFormat(_stime, 'hh');
				let _s_minu = uni.$u.timeFormat(_stime, 'MM');

				this.timeChangeForm.endTime = new Date(_s_year, _s_month - 1, _s_day, _s_houre, _s_minu, 0);

				this.timeChangeForm.NextDate = (this.timeChangeForm.endTime.getDate() != this.timeChangeForm.startTime
					.getDate());
				this.timeChangeForm.endTimeStr = (this.timeChangeForm.NextDate ? '次日' : '') + uni.$u.timeFormat(this
					.timeChangeForm.endTime,
					'hh:MM');

				//刷新试图
				this.refreshView();
			},
			//结束日期选择完成
			confirmTimePickerEnd(e) {
				this.timeChangeForm.NextDate = false;
				this.timeChangeForm.endTime = this.timeChangeForm.startTime;
				console.log(e.value);
				if (e.value[0].indexOf('次日') != -1) {
					let etime = deepClone(this.timeChangeForm.startTime);

					let eetime = etime.setDate(etime.getDate() + 1);
					let _s_year = uni.$u.timeFormat(eetime, 'yyyy');
					let _s_month = uni.$u.timeFormat(eetime, 'mm');
					let _s_day = uni.$u.timeFormat(eetime, 'dd');
					let _s_houre = uni.$u.timeFormat(eetime, 'hh');
					let _s_minu = uni.$u.timeFormat(eetime, 'MM');

					this.timeChangeForm.endTime = new Date(_s_year, _s_month - 1, _s_day, _s_houre, _s_minu, 0);
					this.timeChangeForm.NextDate = true;
				}
				let houre = e.value[0].replaceAll('次日', '').replaceAll('时', '');
				let minute = e.value[1].replaceAll('分', '');
				this.showTimePickerEnd = false;
				this.ydBoxIndex = 10075;

				let _year = uni.$u.timeFormat(this.timeChangeForm.endTime, 'yyyy');
				let _month = uni.$u.timeFormat(this.timeChangeForm.endTime, 'mm');
				let _day = uni.$u.timeFormat(this.timeChangeForm.endTime, 'dd');

				let day = new Date(_year, _month - 1, _day, houre, minute, 0);

				if (day < this.timeChangeForm.startTime) {
					uni.showToast({
						title: '结束时间不能早于开始时间！',
						icon: 'none',
					})
					return;
				}
				let cha = parseInt(Date.parse(day) - Date.parse(this.timeChangeForm.startTime)) /
					1000 / 60 / 60;

				this.timeChangeForm.selectHours = parseFloat(cha / 60).toFixed(1);
				console.log('timeChangeForm.selectHours:', this.timeChangeForm.selectHours, cha, parseFloat(4 / 60)
					.toFixed(1));
				this.timeChangeForm.endTime = day;
				this.timeChangeForm.endTimeStr = (this.timeChangeForm.NextDate ? '次日' : '') + uni.$u.timeFormat(this
					.timeChangeForm.endTime,
					'hh:MM');
				if (cha < this.timeChangeForm.Hours) {
					uni.showToast({
						title: '最少预约' + this.timeChangeForm.Hours + '小时！',
						icon: 'none',
					})
					return;
				}


				//刷新试图
				this.refreshView();
			},
			refreshView() {
				let BeginTime = Date.parse(this.timeChangeForm.startTime);
				let EndTime = Date.parse(this.timeChangeForm.endTime);

				this.TimeRangeInfo.forEach((x) => {
					let startTime = Date.parse(x.startTime); //开始时间
					let endTime = Date.parse(x.endTime); //结束时间
					if (x.state == -1) {
						return;
					}
					x.state = 0;
					//如果开始时间大于等于x.开始时间且开始时间小于x.结束时间
					if (BeginTime >= startTime && BeginTime < endTime) {
						x.state = 1;
					}
					//如果结束时间大于x.开始时间且结束时间小于等于x.结束时间
					if (EndTime > startTime && EndTime <= endTime) {
						x.state = 1;
					}
					//如果开始时间小于x.开始时间且结束时间大于等于x.结束时间
					if (BeginTime < startTime && EndTime >= endTime) {
						x.state = 1;
					}
				});
				console.log("TimeRangeInfo:", this.TimeRangeInfo)
			},
    onCancel() {
      uni.navigateBack()
    }
  }
}
</script>

<style>
.page-body {
  padding: 20px;
}

.page-section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.form-note {
  color: red;
  margin-top: 10px;
}

.form-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>